// pages/orgType/orgType.js
const app = getApp()
var service = require('../../util/service')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    head: {
      currentCity: '',
      placestr: '找品牌或商品'
    },
    swiperImgs: {},
    attribute10:"",
    attribute10Str:"全部",
    title:'',
    orgList: [],
    typeList:[],
    selOrg:0,
    street:1,
    lat: 0,
    lon: 0,
    typeid: "",
    lodding: false,
    loddtext: "加载中……",
    pageSize: 10,
    page: 1,
    sortName:"智能排序",
    sortCode: "",
    sortList: [{ code: "", name: "智能排序" }, { code: "", name: "离我最近" }, { code: "thumbsNumber", name: "好评优先" }, { code: "createdAt", name: "最先发布" }, { code: "lookNumber", name: "人气优先" }, { code: "minPrice", name: "价格最低" }, { code: "maxPrice", name: "价格最高" }],
    bs:"",
    bsurl:"../org/org?",
    cityid:"",
    cityList:[],
    districtList:[]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    var title = options.title||"兴趣才艺";
    var id = options.id;
    wx.setNavigationBarTitle({
      title: title
    }) 
    that.setData({
      'title': title,
      typeid: id,
    })
    
    //获取大图
    service.AJAX("smc/sys/LookupValueLine/listLookupValueLine.json", { "$valHdsCode": "typeImages" }, res => {
      let rows = res;
      for (var i = 0; i < rows.length; i++) {
        rows[i].address = service.imgurl + rows[i].valLnsResult;
      }
      that.setData({
        'swiperImgs': rows
      })
    }, err => { }, 'POST')
    
    //
    // service.find("broadcastImgs", { state: true }, res => {
    //   that.setData({
    //     'swiperImgs': res.data
    //   })
    // }, err => { })

  },
  getCitys:function(){
    var that = this;
    service.AJAX(`smc/base/SystemAddress/querySystemAddress.json?page=1&pagesize=1000&$sid=3&$parentid_addrName-contains=${that.data.head.currentCity}`, {}, res => {
      console.log(res);
      var rows = res.rows;
      that.setData({
        'cityList': rows
      })
      
    }, err => { }, 'POST')
  },
  getDistrictList: function (e) {
    var that = this;
    var cityid = e.target.dataset.id;
    that.setData({
      'cityid': cityid
    })
    if (cityid)
    service.AJAX("smc/base/SystemAddress/querySystemAddress.json?page=1&pagesize=1000&$parentId=" + cityid, {}, res => {
      var rows = res.rows;
      that.setData({
        'districtList': rows
      })
    }, err => { }, 'POST')
    else
      that.setData({
        'districtList': []
      })
  },
  districtclick:function(e){
    var that = this;
    var id = e.currentTarget.dataset.id;
    var name = e.currentTarget.dataset.name;
    console.log(id,name);
    this.setData({
      attribute10: id,
      selOrg: 0,
      'page': 1,
      attribute10Str: name,
      orgList: []
    })
    this.getProvs();
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this
    app.getpol(
      function (currentCity) {
        that.setData({
          'head.currentCity': currentCity,
          'page': 1,
          orgList: []
        })
        that.getCitys();
        //获取所有类型
        service.AJAX("/smc/base/SystemProviderType/listSystemProviderType.json", {}, res => {
          var orgTypes = res;
          that.setData({
            'typeList': orgTypes
          })
          wx.getLocation({
            type: 'wgs84',
            success: function (res) {
              that.setData({
                lat: res.latitude,
                lon: res.longitude,
              });
              that.getProvs();
            }
          });
        }, err => { })
      }
    )
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  selindex:function(){
    this.setData({
      'selOrg': this.data.selOrg != 1?1:0
    })
  },
  selindex2: function () {
    this.setData({
      'selOrg': this.data.selOrg != 2 ? 2 : 0
    })
  },
  selindex3: function () {
    this.setData({
      'selOrg': this.data.selOrg != 3 ? 3 : 0
    })
  },
  clickType:function(item){
    var data = item.currentTarget.dataset;
    this.setData({
      title: data.tname,
      selOrg:0,
      'page': 1,
      typeid: data.tid,
      orgList: []
    })
    wx.setNavigationBarTitle({
      title: data.tname
    })
    this.getProvs();
  },
  getBsToTypeList:function(typeid){
    var bs = "";
    for (var i = 0; i < this.data.typeList.length;i++){
      if (this.data.typeList[i].provTypeId == typeid){
        return this.data.typeList[i].attribute4;
      }
    }
    return bs;
  },
  getProvs: function () {
    var that = this;
    that.setData({
      lodding: true,
      loddtext: "加载中……"
    })
    debugger;
    var bs = this.getBsToTypeList(that.data.typeid);
    if(bs == "SP"){
      service.AJAX("smc/base/SystemProduct/querySystemProduct.json", { page: that.data.page, pageSize: that.data.pageSize,"$attribute2": "SP"}, res => {
        var orgList = res.rows;
        var lodd = orgList.length < 10;
        var orgList2 = [];
        for (var i = 0; i < orgList.length; i++) {
          var ol = {};
          ol.prvId = orgList[i].prodId;
          ol.attribute1 = service.imgurl + orgList[i].prodMainImg;
          ol.prvName = orgList[i].prodName;
          ol.prvDesc = orgList[i].attribute1;
          ol.score = orgList[i].score;
          orgList2.push(ol);         
        }
        var data = that.data.orgList.concat(orgList2);
        that.setData({
          orgList: data,
          lodding: lodd,
          bs: "SP",
          bsurl: "../news/news?type=SP&",
          loddtext: lodd ? "没有更多数据了" : "加载中……"
        })
      }, err => { }, 'POST')
    }else{
      var prame = { page: that.data.page, pageSize: that.data.pageSize, x: that.data.lat, y: that.data.lon, "$provTypeId": that.data.typeid, sortname: this.data.sortCode, "$attribute8": that.data.head.currentCity };
      if (that.data.cityid) prame["$attribute9"] = that.data.cityid;
      if (that.data.attribute10) prame["$attribute10"] = that.data.attribute10;
      service.AJAX("smc/base/SystemProviderUser/querySystemProviderUser.json", prame , res => {
        var orgList = res.rows||[];
        var lodd = orgList.length < 10;
        console.log(orgList);
        for (var i = 0; i < orgList.length; i++) {
          var price = orgList[i].minPrice + "";
          var activitys = orgList[i].prodLabel;
          if (activitys && activitys != "") {
            orgList[i].activity = activitys.split(/[；;]/);
          }
          var prvDesc = orgList[i].prvDesc;
          if (prvDesc && prvDesc.length > 30) {
            orgList[i].prvDesc = prvDesc.substr(0, 30) + "……";
          }
          orgList[i].attribute1 = service.imgurl + orgList[i].attribute1;
          orgList[i].minPrice = price.indexOf(".") > 0 ? price.split(".") : (price + ".00").split(".");
          orgList[i].distance = that.getDistance(that.data.lat, that.data.lon, orgList[i].posX, orgList[i].posY);
          
        }
        var data = that.data.orgList.concat(orgList);
        that.setData({
          orgList: data,
          lodding: lodd,
          bsurl: "../org/org?",
          loddtext: lodd ? "没有更多数据了" : "加载中……"
        })
      }, err => { }, 'POST')
    }
    
  },
  getDistance: function (lat1, lng1, lat2, lng2) {
    lat1 = lat1 || 0;
    lng1 = lng1 || 0;
    lat2 = lat2 || 0;
    lng2 = lng2 || 0;
    var rad1 = lat1 * Math.PI / 180.0;
    var rad2 = lat2 * Math.PI / 180.0;
    var a = rad1 - rad2;
    var b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
    var r = 6378137;
    return ((r * 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(rad1) * Math.cos(rad2) * Math.pow(Math.sin(b / 2), 2)))) / 1000).toFixed(1)
  },
  lower: function () {
    this.setData({
      'page': this.data.page + 1
    })
    this.getProvs();
  },
  clickSort: function (item){
    var data = item.currentTarget.dataset;
    this.setData({
      sortName: data.tname,
      selOrg: 0,
      'page': 1,
      sortCode: data.tid,
      orgList: []
    })
    this.getProvs();
  }
})